package cn.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ChatClient {

    private SocketChannel socketChannel;
    private String host = "127.0.0.1";
    private static final int PORT = 9527;
    private Selector selector;
    private String localFlag;

    /**
     * 初始客户端连接
     *
     * @throws Exception
     */
    public void initClient() throws Exception {
        socketChannel = SocketChannel.open(new InetSocketAddress(host, PORT));
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        localFlag = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("客户端初始化完成..." + localFlag);
    }

    /**
     * 发送消息
     *
     * @param msg
     */
    public void sendMsg(String msg) {
        msg += localFlag + "->" + msg;

        try {
            int write = socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接受消息
     */
    public void receiveMsg() {

        try {
            int channels = selector.select();

            if (channels > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        String readMsg = new String(byteBuffer.array());
                        System.out.println("读取消息:" + readMsg);
                    }
                }
                iterator.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

